#ifndef GameMessageQueue_h__
#define GameMessageQueue_h__

#include "Mutex.h"
#include <list>
#include "GameMessage.h"

typedef std::list<GameMessage*> sMessages;
class GameMessageQueue
{
private:
    sMessages m_list;
    Mutex m_mutex;

public:
    void pushFront(GameMessage* data)
    {
        ScopedMutexLock l(m_mutex);
        sMessages::iterator it = m_list.begin();
        m_list.insert(it, data);
    }
    void UpdateTimeStamps(float dt)
    {
        for(sMessages::iterator it = m_list.begin(); 
            it != m_list.end();
            ++it)
            (*it)->SetTimeStamp((*it)->GetTimeStamp() - dt);
    }
    void push(GameMessage* data)
    {
        ScopedMutexLock l(m_mutex);
        sMessages::iterator it = m_list.begin();
        float tsCache = data->GetTimeStamp();
        while(it != m_list.end())
            if((*it)->GetTimeStamp() > tsCache)
                break;
            else
                ++it;
        m_list.insert(it, data);
    }

    bool empty()
    {
        ScopedMutexLock l(m_mutex);
        return m_list.empty();
    }

    GameMessage* try_pop(bool* worked)
    {
        ScopedMutexLock l(m_mutex);
        if(m_list.empty())
        {
            *worked = false;
            return NULL;
        }
        *worked = true;
        GameMessage* re = (*m_list.begin());
        m_list.erase(m_list.begin());
        return re;
    }

    void clean()
    {
        ScopedMutexLock l(m_mutex);
        sMessages::iterator it = m_list.begin();
        for(; it != m_list.end(); ++it)
        {
            delete (*it);
        }
        m_list.clear();
    }
};


#endif // MessageQueue_h__
